<template>
  <NCard title="数据同步状态" :bordered="false" size="small" class="mb-4">
    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
      <!-- 任务同步状态 -->
      <div class="flex flex-col space-y-2">
        <div class="flex items-center justify-between">
          <span class="text-sm font-medium">任务数据</span>
          <NButton
            size="small"
            type="primary"
            ghost
            :loading="syncLoading.tasks"
            @click="handleManualSync('tasks')"
          >
            手动同步
          </NButton>
        </div>
        <div class="flex items-center space-x-2">
          <NTag :type="getStatusType(syncStatus.tasks)" size="small">
            {{ getStatusText(syncStatus.tasks) }}
          </NTag>
          <span class="text-xs text-gray-500">
            {{ getLastSyncTime(syncStatus.tasksLastSuccessTime) }}
          </span>
        </div>
        <div v-if="syncStatus.tasksLastError" class="text-xs text-red-500">
          错误: {{ syncStatus.tasksLastError }}
        </div>
      </div>

      <!-- 通话记录同步状态 -->
      <div class="flex flex-col space-y-2">
        <div class="flex items-center justify-between">
          <span class="text-sm font-medium">通话记录</span>
          <NButton
            size="small"
            type="primary"
            ghost
            :loading="syncLoading.callRecords"
            @click="handleManualSync('callRecords')"
          >
            手动同步
          </NButton>
        </div>
        <div class="flex items-center space-x-2">
          <NTag :type="getStatusType(syncStatus.callRecords)" size="small">
            {{ getStatusText(syncStatus.callRecords) }}
          </NTag>
          <span class="text-xs text-gray-500">
            {{ getLastSyncTime(syncStatus.callRecordsLastSuccessTime) }}
          </span>
        </div>
        <div v-if="syncStatus.callRecordsLastError" class="text-xs text-red-500">
          错误: {{ syncStatus.callRecordsLastError }}
        </div>
      </div>

      <!-- 剧本同步状态 -->
      <div class="flex flex-col space-y-2">
        <div class="flex items-center justify-between">
          <span class="text-sm font-medium">剧本数据</span>
          <NButton
            size="small"
            type="primary"
            ghost
            :loading="syncLoading.scripts"
            @click="handleManualSync('scripts')"
          >
            手动同步
          </NButton>
        </div>
        <div class="flex items-center space-x-2">
          <NTag :type="getStatusType(syncStatus.scripts)" size="small">
            {{ getStatusText(syncStatus.scripts) }}
          </NTag>
          <span class="text-xs text-gray-500">
            {{ getLastSyncTime(syncStatus.scriptsLastSuccessTime) }}
          </span>
        </div>
        <div v-if="syncStatus.scriptsLastError" class="text-xs text-red-500">
          错误: {{ syncStatus.scriptsLastError }}
        </div>
      </div>
    </div>

    <!-- 全局操作 -->
    <div class="flex justify-end mt-4 pt-4 border-t">
      <NButton
        type="primary"
        :loading="syncLoading.all"
        @click="handleSyncAll"
      >
        同步所有数据
      </NButton>
    </div>
  </NCard>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { NCard, NButton, NTag } from 'naive-ui';
import { fetchSyncStatus, fetchManualSync, fetchSyncAllData } from '@/service/api/outbound';

interface SyncStatus {
  tasks: string;
  callRecords: string;
  scripts: string;
  tasksLastSuccessTime: number;
  callRecordsLastSuccessTime: number;
  scriptsLastSuccessTime: number;
  tasksLastError: string;
  callRecordsLastError: string;
  scriptsLastError: string;
  tasksLastErrorTime: number;
  callRecordsLastErrorTime: number;
  scriptsLastErrorTime: number;
}

const syncStatus = ref<SyncStatus>({
  tasks: 'UNKNOWN',
  callRecords: 'UNKNOWN',
  scripts: 'UNKNOWN',
  tasksLastSuccessTime: 0,
  callRecordsLastSuccessTime: 0,
  scriptsLastSuccessTime: 0,
  tasksLastError: '',
  callRecordsLastError: '',
  scriptsLastError: '',
  tasksLastErrorTime: 0,
  callRecordsLastErrorTime: 0,
  scriptsLastErrorTime: 0
});

const syncLoading = ref({
  tasks: false,
  callRecords: false,
  scripts: false,
  all: false
});

let statusTimer: NodeJS.Timeout | null = null;

// 获取状态类型
const getStatusType = (status: string) => {
  switch (status) {
    case 'SUCCESS':
      return 'success';
    case 'RUNNING':
      return 'warning';
    case 'FAILED':
      return 'error';
    default:
      return 'default';
  }
};

// 获取状态文本
const getStatusText = (status: string) => {
  switch (status) {
    case 'SUCCESS':
      return '成功';
    case 'RUNNING':
      return '同步中';
    case 'FAILED':
      return '失败';
    default:
      return '未知';
  }
};

// 获取最后同步时间
const getLastSyncTime = (timestamp: number) => {
  if (!timestamp) return '从未同步';
  const date = new Date(timestamp);
  return date.toLocaleString('zh-CN');
};

// 获取同步状态
const getSyncStatus = async () => {
  try {
    const response = await fetchSyncStatus();
    if (response.data) {
      syncStatus.value = response.data;
    }
  } catch (error) {
    console.error('获取同步状态失败:', error);
  }
};

// 手动同步
const handleManualSync = async (type: 'tasks' | 'callRecords' | 'scripts') => {
  try {
    syncLoading.value[type] = true;
    await fetchManualSync(type);
    window.$message.success(`${type}同步已启动`);
    // 等待一下再刷新状态
    setTimeout(() => {
      getSyncStatus();
    }, 1000);
  } catch (error) {
    window.$message.error(`${type}同步启动失败`);
    console.error('同步启动失败:', error);
  } finally {
    syncLoading.value[type] = false;
  }
};

// 同步所有数据
const handleSyncAll = async () => {
  try {
    syncLoading.value.all = true;
    await fetchSyncAllData();
    window.$message.success('所有数据同步已启动');
    // 等待一下再刷新状态
    setTimeout(() => {
      getSyncStatus();
    }, 1000);
  } catch (error) {
    window.$message.error('所有数据同步启动失败');
    console.error('同步启动失败:', error);
  } finally {
    syncLoading.value.all = false;
  }
};

// 定时刷新状态
const startStatusTimer = () => {
  statusTimer = setInterval(() => {
    getSyncStatus();
  }, 30000); // 每30秒刷新一次
};

// 停止定时器
const stopStatusTimer = () => {
  if (statusTimer) {
    clearInterval(statusTimer);
    statusTimer = null;
  }
};

onMounted(() => {
  getSyncStatus();
  startStatusTimer();
});

onUnmounted(() => {
  stopStatusTimer();
});
</script>
